package eerbaar.internal.game;

import java.util.ArrayList;
import java.util.List;

import eerbaar.area.AreaFactory;
import eerbaar.area.IArea;
import eerbaar.elements.IElement;
import eerbaar.game.IGame;
import eerbaar.level.ILevel;
import eerbaar.level.LevelFactory;
import eerbaar.persona.IPersona;
import eerbaar.pet.PetFactory;

public class Game implements IGame {

    private IArea area;

    private ILevel level;

    public Game() {
        this.area = AreaFactory.createArea(10, 10);
        this.level = LevelFactory.create(0, "");

        if (this.getPersona("pet") == null) {
            populatePlayer();
        }
    }

    public Game(IArea area, ILevel level) {
        this.area = area;
        this.level = level;
    }

    public void addPersona(IPersona persona) {
        this.area.addElement(persona);
    }

    @Override
    public IArea getArea() {
        return this.area;
    }

    @Override
    public ILevel getLevel() {
        return this.level;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends IPersona> T getPersona(Class<T> type, String name) {

        IPersona result = null;

        IPersona[] personas = getPersonas();
        for (IPersona e : personas) {

            String test = e.getName();
            if (test.equals(name)) {
                result = e;
                break;
            }
        }

        return (T) result;
    }

    @Override
    public IPersona getPersona(String name) {
        return getPersona(IPersona.class, name);
    }

    @Override
    public IPersona[] getPersonas() {

        List<IPersona> result = new ArrayList<IPersona>();

        for (IElement e : this.area.getElements()) {

            if ((e instanceof IPersona) == false) {
                continue;
            }

            result.add((IPersona) e);
        }

        return result.toArray(new IPersona[] {});
    }

    @Override
    public void init() {

        if (this.getPersona("pet") == null) {
            populatePlayer();
        }

        if (this.level != null) {
            this.level.start(this);
        }
    }

    public void populatePlayer() {
        addPersona(PetFactory.create(5, 9));
    }

    public void removePersona(IPersona persona) {
        this.area.removeElement(persona);
    }

    @Override
    public void setArea(IArea area) {
        this.area = area;
    }

    @Override
    public void setLevel(ILevel level) {
        this.level = level;
    }

    @Override
    public void term() {

        if (this.level != null) {
            this.level.stop();
        }
    }

}
